package com.github.rpc4j.producer.service;

import java.util.concurrent.ConcurrentHashMap;

import com.github.rpc4j.common.ServiceRequest;
import com.github.rpc4j.common.ServiceResponse;
import com.github.rpc4j.producer.core.Rpc4jProducerContext;

public class Rpc4jServicePool implements ServicePool{
	
	private  Rpc4jProducerContext context; 
	private  ConcurrentHashMap<String,ConcurrentHashMap<String,Rpc4jService>> serverMap = new ConcurrentHashMap<String,ConcurrentHashMap<String,Rpc4jService>>();
	
	public Rpc4jServicePool(Rpc4jProducerContext context){
		this.context = context;
	}
	
	@Override
	public void addService(Service service) {
		Rpc4jService rService = new Rpc4jService(service);
		context.getZkUtil().registerService(service);
		ConcurrentHashMap<String,Rpc4jService> serviceMap  = serverMap.get(service.getServiceInterface());
		if(serviceMap==null){
			serviceMap = new ConcurrentHashMap<String,Rpc4jService>();
			serverMap.put(service.getServiceInterface(), serviceMap);
		}
		serviceMap.put(service.getVersion(), rService);
	}


	@Override
	public  ServiceResponse callService(ServiceRequest request) {
		ConcurrentHashMap<String,Rpc4jService> serviceMap  = serverMap.get(request.getInterfaceName());
		Rpc4jService rpc4jService  = serviceMap.get(request.getVersion());
		Object  result = null;
		Throwable throwable = null;
		try{
			result = rpc4jService.invoke(request);
		}catch(Throwable e){
			throwable = e;
		}
	    ServiceResponse response = new ServiceResponse();
	    response.setResult(result);
	    response.setThrowable(throwable);
	    return response;
	}
	
	
	
	
	
	
	

}
